// 从 .env 文件加载环境变量
import { load } from "dotenv";
await load({ export: true });

interface AppConfig {
  server: {
    port: number;
    host: string;
  };
  auth: {
    jwtSecret: string;
    initialUsers: Array<{
      id: string;
      username: string;
      password: string;
    }>;
  };
  api: {
    serverUrl: string;
    workspaceKey: string;
    scope: string;
  };
}

// 默认配置
const defaultConfig: AppConfig = {
  server: {
    // 优先使用环境变量中的 PORT，如果没有则使用默认值
    port: Number(Deno.env.get("PORT")) || 8000,
    host: "localhost",
  },
  auth: {
    // 确保生产环境必须提供 JWT_SECRET
    jwtSecret: (() => {
      const secret = Deno.env.get("JWT_SECRET");
      if (Deno.env.get("DENO_ENV") === "production" && !secret) {
        throw new Error("JWT_SECRET must be set in production environment");
      }
      return secret ?? "your-secret-key";
    })(),
    initialUsers: [{
      id: "1",
      username: "admin",
      password: "123123"
    }]
  },
  api: {
    serverUrl: Deno.env.get("API_SERVER_URL") ?? "https://23920.dev.d8dcloud.com",
    workspaceKey: Deno.env.get("WORKSPACE_KEY") ?? "ws_jriefsvehkb",
    scope: "user"
  }
};

console.log(defaultConfig);

// 根据不同环境加载不同配置
const env = Deno.env.get("DENO_ENV") ?? "development";

const envConfigs: Record<string, Partial<AppConfig>> = {
  development: {
    // 开发环境特定配置
  },
  production: {
    // 生产环境特定配置
    server: {
      port: 80,
      host: "0.0.0.0",
    }
  },
  test: {
    // 测试环境特定配置
  }
};

// 合并默认配置和环境特定配置
export const config: AppConfig = {
  ...defaultConfig,
  ...envConfigs[env]
};

// 导出一些常用的配置getter
export const getServerConfig = () => config.server;
export const getAuthConfig = () => config.auth;
export const getApiConfig = () => config.api;